/*
 * Copyright (c) 2020 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.github.piasy.rxscreenshotdetector.example;

import ohos.aafwk.ability.Ability;
import ohos.aafwk.ability.DataAbilityHelper;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Button;
import ohos.agp.components.Text;
import ohos.bundle.IBundleManager;
import ohos.data.resultset.ResultSet;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.media.photokit.metadata.AVStorage;
import ohos.security.SystemPermission;
import ohos.utils.net.Uri;

import com.github.piasy.rxscreenshotdetector.RxScreenshotDetector;

import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.schedulers.Schedulers;

import io.reactivex.rxjava3.openharmony.schedulers.OpenHarmonySchedulers;

import java.util.Locale;

/**
 * Main Ability for the UI screen
 */
public class MainAbility extends Ability {
    private static final HiLogLabel LABEL_LOG = new HiLogLabel(3, 0xD000F00, MainAbility.class.getSimpleName());
    private static final String[] PROJECTION = new String[]{
            AVStorage.Images.Media.DISPLAY_NAME, AVStorage.Images.Media.DATA,
            AVStorage.Images.Media.DATE_ADDED
    };
    private int PERMISSION_REQUEST_CODE = 2;

    private Text mTextView;
    private Disposable observable = null;
    private boolean isAbilityStarted = false;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);

        isAbilityStarted = true;

        mTextView = (Text) findComponentById(ResourceTable.Id_mText);
        Button mBtnTest = (Button) findComponentById(ResourceTable.Id_mBtnTest);

        mBtnTest.setClickedListener(component -> getAllMedia());

        if (RxScreenshotDetector.checkPermission(this)) {
            observable = RxScreenshotDetector.start(this)
                    .subscribeOn(Schedulers.io())
                    .observeOn(OpenHarmonySchedulers.mainThread())
                    .subscribe(path -> mTextView.setText(mTextView.getText() + "\nScreenshot: " + path),
                            Throwable::printStackTrace);
        } else {
            requestPermissionsFromUser(new String[]{SystemPermission.READ_USER_STORAGE}, PERMISSION_REQUEST_CODE);
        }
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    @Override
    protected void onStop() {
        super.onStop();
        isAbilityStarted = false;
        if (observable != null) {
            observable.dispose();
        }
    }

    @Override
    public void onRequestPermissionsFromUserResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == PERMISSION_REQUEST_CODE) {
            if (grantResults.length > 0) {
                if (grantResults[0] == IBundleManager.PERMISSION_GRANTED) {
                    if (isAbilityStarted) {
                        observable = RxScreenshotDetector.start(this)
                                .subscribeOn(Schedulers.io())
                                .observeOn(OpenHarmonySchedulers.mainThread())
                                .subscribe(path -> mTextView.setText(mTextView.getText() + "\nScreenshot: " + path),
                                        Throwable::printStackTrace);
                    }
                } else {
                    requestPermissionsFromUser(
                            new String[]{SystemPermission.READ_USER_STORAGE},
                            PERMISSION_REQUEST_CODE);
                }
            }
        }
        super.onRequestPermissionsFromUserResult(requestCode, permissions, grantResults);
    }

    private void getAllMedia() {
        DataAbilityHelper dataAbilityHelper = DataAbilityHelper.creator(this);
        ResultSet resultSet = null;
        try {
            resultSet = dataAbilityHelper.query(Uri.parse("dataability:///media/external/images/media"),
                    PROJECTION, null);
            if (resultSet != null) {
                while (resultSet.goToNextRow()) {
                    String path = resultSet.getString(
                            resultSet.getColumnIndexForName(AVStorage.Images.Media.DATA));
                    long dateAdded = resultSet.getLong(
                            resultSet.getColumnIndexForName(AVStorage.Images.Media.DATE_ADDED));
                    long currentTime = System.currentTimeMillis() / 1000;
                    HiLog.info(LABEL_LOG, String.format(Locale.ROOT, "%s","path: " + path + ", dateAdded: " + dateAdded + ", currentTime: " + currentTime));
                }
            }
        } catch (Exception e) {
            HiLog.info(LABEL_LOG, String.format(Locale.ROOT, "%s","open result set failed: " + e.getMessage()));
        } finally {
            if (resultSet != null) {
                resultSet.close();
            }
        }
    }
}
